﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.IO;
using Tools.File;

namespace Tools.Debugging {
    public enum Level { All = 0, Info = 10, Notice = 20, Log = 30, Debug = 40, Warning = 50, Error = 60, Panic = 99, None = 100 };

    public enum LoggerType { TextLogger, DbLogger };
    public enum LoggerSubType { Console, File, TextWriter };

    public class Debug {

        public static ILogger logger = new TextLogger( );

        public static void init ( LoggerType type, LoggerSubType subType, object data ) {
            switch ( type ) {
                default:
                case LoggerType.TextLogger:
                    switch ( subType ) {
                        case LoggerSubType.Console:
                            Debug.logger = new TextLogger( );
                            break;
                        case LoggerSubType.File:
                            Debug.logger = new TextLogger( ( string ) data );
                            break;
                        case LoggerSubType.TextWriter:
                            Debug.logger = new TextLogger( ( TextWriter ) data );
                            break;
                    };
                    break;
            }
        }

    }

    public class TextLogger : ILogger {
        protected TextWriter Out;

        protected Level logLevel = Level.All;

        public TextLogger ( TextWriter writer ) {
            this.Out = writer;
        }

        public TextLogger ( ) {
            this.Out = Console.Out;
        }

        public TextLogger ( String fileName ) {
            PathEx path = new PathEx( fileName );
            path.fileName = path.fileName + "_" + DateTime.Now.ToString( "yyyyMMdd_HHmmss" );
            Console.WriteLine( "Debuging file created: {0}", path.ToString( ) );
            FileStream s = System.IO.File.Create( path.ToString( ) );
            this.Out = new StreamWriter( s );
        }

        public Level LogLevel ( Level level ) {
            Level oldLevel = this.logLevel;
            this.logLevel = level;
            return oldLevel;
        }

        public void Log ( String format, params object[] objs ) {
            //this.Out.WriteLine("*** "+DateTime.Now.ToString("u")+" *****");

            this.Out.WriteLine( format, objs );
            //this.Out.WriteLine("------------------------------------------");
            this.Out.Flush( );
        }

        public void Log ( Level level, String format, params object[] objs ) {
            if ( level >= this.logLevel ) {
                this.Log( format, objs );
            }
        }
    }
    public interface ILogger {
        void Log ( String format, params object[] objs );
        void Log ( Level level, String format, params object[] objs );

        Level LogLevel ( Level level );
    }

}
